package com.yang.sso.resource.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.yang.sso.resource.handler.MyAccessDeniedHandler;
import com.yang.sso.resource.point.MyAuthenticationEntryPoint;
import com.yang.sso.resource.properties.SecurityProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

import java.util.List;

/**
 * @author zhouyang
 * @version v1.1
 * @date 2024/9/25 00:01
 * @description 资源服务器 Security配置
 */
@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(jsr250Enabled = true, securedEnabled = true)
public class ResourceServerConfig {

    private final SecurityProperties securityProperties;
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        List<String> whitePaths = securityProperties.getWhitePaths();
        http.authorizeHttpRequests((authorize) -> {
                            if (CollectionUtil.isNotEmpty(whitePaths)) {
                                log.info("放行路由:{}",whitePaths);
                                authorize.requestMatchers(Convert.toStrArray(whitePaths)).permitAll();
                            }
                            authorize.anyRequest().authenticated();
                        }
                )
                // 使用jwt处理接收到的access token
                .oauth2ResourceServer((oauth2ResourceServer) -> oauth2ResourceServer
                        .jwt(Customizer.withDefaults())
                        .authenticationEntryPoint(new MyAuthenticationEntryPoint())
                        .accessDeniedHandler(new MyAccessDeniedHandler())

                );

        return http.build();
    }

}
